package com.alter.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alter.model.SeNavBar;
import com.alter.system.dao.SeNavBarDao;
import com.alter.system.service.SysUIService;

@Service
@Transactional(readOnly = true)
public class SysUIServiceImpl implements SysUIService {

    @Autowired(required = false)
    private SeNavBarDao barDao;

    @Override
    public List<SeNavBar> getSysNavBarList() {
	List<SeNavBar> list = new ArrayList<SeNavBar>();
	list = barDao.find(Restrictions.eq("level", 1),Restrictions.eq("isEnabled", Boolean.TRUE));
	return list;
    }

    @Override
    public List<SeNavBar> getChildNavList(String headerNavAid) {
	return barDao.find(Restrictions.eq("parentBar.aid", headerNavAid));
    }

    @Override
    public List<SeNavBar> getsystemNavTree(SeNavBar bar) {
	List<SeNavBar> list;
	if (bar == null) {
	    list = barDao.find(Restrictions.eq("level", 1));
	} else {
	    list = barDao.find(Restrictions.eq("parentBar.aid", bar.getAid()));
	    bar.setChildBar(list);
	}
	for (SeNavBar seNavBar : list) {
	    getsystemNavTree(seNavBar);
	}
	return list;
    }
    
    @Override
    public List<SeNavBar> getsystemParentNavTree(String barCode) {
	return null;
    }

    @Override
    public List<SeNavBar> getAllSeNavBar() {
	return barDao.getAll();
    }

    @Override
    @Transactional
    public SeNavBar updateSeNav(SeNavBar bar) {
	SeNavBar _bar = barDao.get(bar.getAid());
	// 提供修改功能的字段
	_bar.setName(bar.getName());
	_bar.setHref(bar.getHref());
	_bar.setDesc(bar.getDesc());
	_bar.setIsEnabled(bar.getIsEnabled() == null ? Boolean.FALSE : bar.getIsEnabled());
	barDao.updateNavbar(_bar);
	return _bar;
    }

    /**
     * <p>
     * 初始化 bar code 信息
     * </p>
     */
    private void initSeNavBar(SeNavBar bar) {
	// checkBox value is no in HTML. bind error.
	if (bar.getIsEnabled() == null) {
	    bar.setIsEnabled(Boolean.FALSE);
	}
	SeNavBar _pbar = bar.getParentBar();
	if (_pbar == null) {
	    bar.setLevel(1);
	} else {
	    bar.setLevel(_pbar.getLevel() + 1);
	}
    }

    @Override
    @Transactional
    public void createSeNav(SeNavBar bar) {
	if ("".equals(bar.getAid())) {
	    bar.setAid(null);
	}
	//String _pId = bar.getParentBar().getAid();\
	SeNavBar _pBar = bar.getParentBar();
	if (_pBar != null) {
	    bar.setParentBar(barDao.get(_pBar.getAid()));
	}
	initSeNavBar(bar);
	barDao.save(bar);
    }

    @Override
    @Transactional
    public void delSeNav(SeNavBar bar) {
	barDao.delete(bar.getAid());
    }

}
